import 'dart:io';

import 'package:package_info/package_info.dart';
import '../../config/AppInfo.dart';
import '../../main.dart';

import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';

import '../../model/UserEntity.dart';
import '../../utils/Tool/MyTools.dart';
import '../ApiUtils.dart';
import '../R.dart';

/**
 * 用户信息请求相关
 * 比如登录，注册，发送验证码，修改用户信息等
 */

///使用md5加密
String generateMD5(String data) {
  Uint8List content = new Utf8Encoder().convert(data);
  Digest digest = md5.convert(content);
  return digest.toString();
}

/// 获取微信授权
// Future<Map<String, dynamic>> api_wx_access_token(String code) async {
//   Map<String, dynamic> map = {};
//   print("api_wx_access_token = $map");
//   dynamic methodAwait = await ApiUtils.methodAwait(ApiUtils.postMethod,
//       "https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WXConfig.wxAppId}&secret=${WXConfig.wxSecret}&code=${code}&grant_type=authorization_code",
//       param: map, isUseBaseUrl: false);
//   print("api_wx_access_token = ${methodAwait}");
//
//   return methodAwait;
// }

/// 获取微信用户信息
Future<Map<String, dynamic>> api_wx_userinfo(
    String access_token, String openid) async {
  Map<String, dynamic> map = {};
  print("api_wx_userinfo = $map");
  dynamic methodAwait = await ApiUtils.methodAwait(ApiUtils.postMethod,
      "https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}",
      param: map, isUseBaseUrl: false);
  print("api_wx_userinfo = ${methodAwait}");

  print("json\n\n = ${json.encode(methodAwait)}\n\n");

  return methodAwait;
}

/// @description: 微信登录
/// @return {*}
Future<R> api_wechat_login(String code) async {
  String url = "/api/v1.oauth/common/app/type/wechat/appid/$AppId/code/$code";
  dynamic methodAwait = await ApiUtils.methodAwait(ApiUtils.getMethod, url);

  R r = R.fromData(methodAwait);

  return r;
}

/// @description: 绑定微信（Authorization的参数已经在公共方法中设置，所以看起来和微信登录是一致的）
/// @return {*}
Future<R> api_wechat_bind(String code) async {
  String url = "/api/v1.oauth/common/app/type/wechat/appid/$AppId/code/$code";
  dynamic methodAwait = await ApiUtils.methodAwait(ApiUtils.getMethod, url);

  R r = R.fromData(methodAwait);

  return r;
}

/// 短信验证码
/// type:类型(0:注册,1:登录,2:找回密码)
Future<R> api_userInfo_send(String phone, String type,
    {String? csid, String? imgCode, int cssw = 0}) async {
  Map<String, dynamic> map = Map();
  map['phone'] = phone;
  map['cssw'] = cssw;
  map['dispatch'] = "1";
  map['type'] = type;
  if (csid != null) map['csid'] = csid;
  if (imgCode != null) map['code'] = imgCode;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.sms/send',
      param: map);

  R r = R.fromData(methodAwait);
  return r;
}



/// 用户绑定手机号
Future<R> api_userInfo_bindPhone(
    {String? type, String? phone, String? ssid, String? code}) async {
  Map<String, dynamic> map = Map();
  map['type'] = type;
  map['content'] = phone;
  map['ssid'] = ssid;
  map['code'] = code;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.user/bound',
      param: map);

  R r = R.fromData(methodAwait);
  return r;
}

/// 用户注册
Future<R> api_userInfo_register({
  required String type,
  String? phone,
  String? code,
  String? pwd,
  String? ssid,
  String? identifier,
}) async {
  Map<String, dynamic> map = Map();

  if (type == '0') {
    //0:用户名密码[username+password]
  } else if (type == '1') {
    //1:手机密码[phone+password]
  } else if (type == '2') {
    //2:手机验证码[phone+ssid+code+(可选password)]
    map['type'] = type;
    map['phone'] = phone;
    map['password'] = generateMD5(pwd!);
    map['ssid'] = ssid;
    map['code'] = code;
    map['exist'] = 0;
  } else if (type == '4') {
    //唯一标识符[identifier]
    map['type'] = type;
    map['identifier'] = identifier;
    map['exist'] = 1;
  }

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/register',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    print("map = $map");

    return map;
  });

  return r;
}

/// 用户登录
Future<R> api_userInfo_login(
    {required String type,
    String? phone,
    String? pwd,
    String? ssid,
    String? code,
    String? identifier}) async {
  Map<String, dynamic> map = Map();
  map['type'] = type;

  if (type == '0') {
    //0:用户名密码[username+password]
  } else if (type == '1') {
    //1:手机密码[phone+password],
    map['phone'] = phone!;
    map['password'] = generateMD5(pwd!);
  } else if (type == '2') {
    //2:手机验证码[phone+ssid+code],
    map['phone'] = phone!;
    map['ssid'] = ssid!;
    map['code'] = code!;
  } else if (type == '4') {
    //4:唯一标识符[identifier]
    map['identifier'] = identifier!;
  }

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/login',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/// 找回密码
Future<R> api_userInfo_findpw(
    String phone, String pwd, String code, String ssid) async {
  Map<String, dynamic> map = Map();
  map['content'] = phone;
  map['passwd'] = generateMD5(pwd);
  map['ssid'] = ssid;
  map['code'] = code;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/findpw',
      param: map);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}



// /// 用户头像列表
// Future<R> api_userInfo_avatars(
//     {required String page, required String limit}) async {
//   Map<String, dynamic> params = Map();
//   params['page'] = page;
//   params['limit'] = limit;
//   dynamic methodAwait = await ApiUtils.methodAwait(
//       ApiUtils.postMethod, '/api/v1.common/avatars',
//       param: params);
//
//   R r = R.fromData(methodAwait, handlerData: (map) {
//     List<SelectAvatorEntity> dataList = [];
//     if (MyTools.listIsEmpty(map)) return dataList;
//     for (Map<String, dynamic> item in map as List) {
//       dataList.add(SelectAvatorEntity.fromJson(item));
//     }
//     return dataList;
//   });
//
//   return r;
// }

/// 用户信息修改
Future<R> api_userInfo_modify(
    {String? nickname, String? avatar, String? sex, String? birthday}) async {
  Map<String, dynamic> params = Map();
  if (!MyTools.stringIsEmpty(nickname)) params['nickname'] = nickname;
  if (!MyTools.stringIsEmpty(avatar)) params['avatar'] = avatar;
  if (!MyTools.stringIsEmpty(sex)) params['sex'] = sex;
  if (!MyTools.stringIsEmpty(birthday)) params['birthday'] = birthday;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.user/modify',
      param: params);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/// 实名认证
/// type :类型 [0:realname+idcard_no]
Future<R> api_userInfo_certification(
    {String? type, String? realname, String? idcard_no}) async {
  Map<String, dynamic> params = Map();
  params['type'] = type;
  params['realname'] = realname;
  params['idcard_no'] = idcard_no;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.user/certification',
      param: params);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/// app意见反馈
/// content: 内容
/// contact_way：联系方式
///
Future<R> api_userInfo_feedback(
    {String? content,
    String? contact_way,
    String? title,
    String? app_title,
    String? app_id,
    List<String>? images}) async {
  Map<String, dynamic> params = Map();

  if (!MyTools.stringIsEmpty(content)) params['content'] = content;
  if (!MyTools.stringIsEmpty(contact_way)) params['contact_way'] = contact_way;
  if (!MyTools.stringIsEmpty(title)) params['title'] = title;
  if (!MyTools.stringIsEmpty(app_title)) params['app_title'] = app_title;
  if (!MyTools.stringIsEmpty(app_id)) params['app_id'] = app_id;
  if (!MyTools.listIsEmpty(images)) params['images'] = images!;

  params['device'] = Platform.isAndroid ? 1 : 2; // 设备 [0:默认,1:Android,2:IOS]
  PackageInfo info = await PackageInfo.fromPlatform();
  params['versions'] = info.version;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, 'api/v1.common/feedback',
      param: params);

  R r = R.fromData(methodAwait, handlerData: (map) {
    return map;
  });

  return r;
}

/// 第三方登录授权信息
/// content: 内容
///
Future<R> api_userInfo_third() async {
  dynamic methodAwait =
      await ApiUtils.methodAwait(ApiUtils.postMethod, '/api/v1.user/third');

  R r = R.fromData(methodAwait, handlerData: (map) {
    List list = [];

    if (!MyTools.listIsEmpty(map)) {
      for (var item in map) {
       //  list.add(BindThirdEntity.fromJson(item));
      }
    }
    return list;
  });

  return r;
}

/// @description: 账号检测
/// @return {*}
Future<R> api_account_accheck(
    {int type = 1, String? phone, String? username, String? identifier}) async {
  Map<String, dynamic> params = Map();
  params['type'] = type;

  if (phone != null) {
    params['phone'] = phone;
  }

  if (username != null) {
    params['username'] = username;
  }

  if (identifier != null) {
    params['identifier'] = identifier;
  }

  String url = "/api/v1.common/accheck";
  dynamic methodAwait =
      await ApiUtils.methodAwait(ApiUtils.postMethod, url, param: params);

  R r = R.fromData(methodAwait);

  return r;
}

/// @description: 敏感词检测
/// @return {*}
Future<R> api_sensitive_accheck(String content, {int type = 0}) async {
  Map<String, dynamic> params = Map();
  params['content'] = content;
  params['type'] = type;

  String url = "/api/v1.common/sensitive";
  dynamic methodAwait =
      await ApiUtils.methodAwait(ApiUtils.postMethod, url, param: params);

  R r = R.fromData(methodAwait);

  return r;
}

/// 获取图形验证码
Future<R> api_image_code() async {
  dynamic methodAwait =
      await ApiUtils.methodAwait(ApiUtils.postMethod, 'api/v1.common/captcha');

  return R.fromData(methodAwait);
}

/// 删除帐号，仅 debug 可用
Future<R> api_logoff({String? phone, String? ssid, String? code}) async {
  Map<String, dynamic> params = Map();

  if (phone != null) params['phone'] = phone;
  if (ssid != null) params['ssid'] = ssid;
  if (code != null) params['code'] = code;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, 'api/v1.user/logoff',
      param: params);

  return R.fromData(methodAwait);
}

/// 检测注销帐号状态
Future<R> api_is_logoff() async {
  dynamic methodAwait = await ApiUtils.methodAwait(
    ApiUtils.postMethod,
    'api/v1.user/islogoff',
  );

  return R.fromData(methodAwait);
}

/// 获取用户扩展信息
// Future<R> api_userInfo_extend() async {
//   dynamic methodAwait =
//       await ApiUtils.methodAwait(ApiUtils.postMethod, '/api/v1.user/extend');
//
//   R r = R.fromData(methodAwait, handlerData: (map) {
//     if (!MyTools.mapIsEmpty(map)) {
//       Map result = map as Map;
//
//       String? registrationId = result.containsKey('registration_id')
//           ? result['registration_id']
//           : null;
//       String? isPush =
//           result.containsKey('is_push') ? result['is_push'].toString() : null;
//
//       UserEntity? userEntity = UserBlocTool.userEntity;
//       if (userEntity != null) {
//         userEntity.registrationId = registrationId;
//         userEntity.isPush = isPush;
//         UserBlocTool.update(navigatorKey.currentState!.context, userEntity);
//       }
//     }
//     return map;
//   });
//
//   return r;
// }

/// iOS采用静默登录
Future<R> api_ios_Login(String unicode) async {
  Map<String, dynamic> map = Map();
  map['identifier'] = unicode;
  map['type'] = 4;
  map['exist'] = 1;

  dynamic methodAwait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, 'api/v1.common/register',
      extra: {"login": true}, param: map);

  return R.fromData(methodAwait);
}
